import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:mesh/function/widgets/border_widget.dart';
import '../models/group_chat_model.dart';
import '../states/team_conversation_state.dart';
import '../states/user_state.dart';
import '../widgets/animated_tap_widget.dart';
import '../widgets/toast_widget.dart';

/// 群聊信息弹窗组件
class GroupInfoDialog extends StatelessWidget {
  final GroupChatModel group;

  const GroupInfoDialog({super.key, required this.group});

  /// 显示群聊信息弹窗
  static Future<void> show(BuildContext context, GroupChatModel group) {
    return showGeneralDialog<void>(
      context: context,
      barrierDismissible: true,
      barrierLabel: '',
      barrierColor: Colors.black.withOpacity(0.5),
      transitionDuration: const Duration(milliseconds: 300),
      pageBuilder: (
        BuildContext context,
        Animation<double> animation,
        Animation<double> secondaryAnimation,
      ) {
        return GroupInfoDialog(group: group);
      },
      transitionBuilder: (
        BuildContext context,
        Animation<double> animation,
        Animation<double> secondaryAnimation,
        Widget child,
      ) {
        return FadeTransition(
          opacity: animation,
          child: ScaleTransition(
            scale: Tween<double>(begin: 0.8, end: 1.0).animate(
              CurvedAnimation(parent: animation, curve: Curves.easeOutBack),
            ),
            child: child,
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    // 获取群聊创建者信息
    final creatorInfo = TeamConversationState.getUserInfo(group.creatorId);
    final creatorName = creatorInfo?['userName'] ?? 'Unknown';

    // 格式化创建时间
    final createTime =
        '${group.createTime.year}/${group.createTime.month.toString().padLeft(2, '0')}/${group.createTime.day.toString().padLeft(2, '0')}';

    return Dialog(
      backgroundColor: Colors.transparent,
      elevation: 0,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 主要内容容器和装饰图片的 Stack
          Stack(
            clipBehavior: Clip.none,
            children: [
              // 装饰图片 - 在 z 轴下方
              Positioned(
                top: -90.h, // 向上位移，露出一半
                right: 20.w, // 水平居中
                left: 20.w,
                child: Image.asset(
                  'assets/images/sun.png',
                  width: 160.w,
                  height: 160.w,
                ),
              ),

              // 主要内容容器
              Container(
                width: 320.w,
                decoration: BoxDecoration(
                  color: const Color(0xFF663507),
                  borderRadius: BorderRadius.circular(24.r),
                ),
                child: Stack(
                  children: [
                    // 右上角关闭按钮
                    Positioned(
                      top: 2.w,
                      right: 2.w,
                      child: AnimatedTapButton(
                        onTap: () => Navigator.of(context).pop(),
                        child: Container(
                          width: 32.w,
                          height: 32.w,
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.1),
                            shape: BoxShape.circle,
                          ),
                          child: Icon(
                            Icons.close,
                            color: Colors.white,
                            size: 20.w,
                          ),
                        ),
                      ),
                    ),

                    // 内容
                    Padding(
                      padding: EdgeInsets.all(24.w),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          // 创建者信息
                          Text.rich(
                            TextSpan(
                              children: [
                                TextSpan(
                                  text: creatorName,
                                  style: TextStyle(
                                    color: const Color(0xFFFF8A3C),
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w600,
                                    fontFamily:
                                        GoogleFonts.quicksand(
                                          fontWeight: FontWeight.w600,
                                        ).fontFamily,
                                  ),
                                ),
                                TextSpan(
                                  text: " Posted 'Play Together'",
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w400,
                                    fontFamily:
                                        GoogleFonts.quicksand(
                                          fontWeight: FontWeight.w400,
                                        ).fontFamily,
                                  ),
                                ),
                              ],
                            ),
                            textAlign: TextAlign.center,
                          ),

                          SizedBox(height: 16.h),

                          // 位置信息
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.location_on,
                                color: const Color(0xFFFF8A3C),
                                size: 16.w,
                              ),
                              SizedBox(width: 4.w),
                              Container(
                                constraints: BoxConstraints(maxWidth: 200.w),
                                child: Text(
                                      group.location,
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                    )
                                    .fontSize(14.sp)
                                    .textColor(Colors.white)
                                    .fontWeight(FontWeight.w500)
                                    .fontFamily(
                                      GoogleFonts.quicksand(
                                        fontWeight: FontWeight.w500,
                                      ).fontFamily,
                                    ),
                              ),
                            ],
                          ),

                          SizedBox(height: 8.h),

                          // 创建时间
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.access_time,
                                color: const Color(0xFFFF8A3C),
                                size: 16.w,
                              ),
                              SizedBox(width: 4.w),
                              Text(createTime)
                                  .fontSize(14.sp)
                                  .textColor(Colors.white)
                                  .fontWeight(FontWeight.w500)
                                  .fontFamily(
                                    GoogleFonts.quicksand(
                                      fontWeight: FontWeight.w500,
                                    ).fontFamily,
                                  ),
                            ],
                          ),

                          SizedBox(height: 20.h),

                          // 群聊封面图片
                          Container(
                            width: 180.w,
                            height: 200.h,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(12.r),
                              image: DecorationImage(
                                image: AssetImage(group.groupCoverImage),
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),

                          SizedBox(height: 25.h), // 为按钮留出空间
                        ],
                      ),
                    ),
                  ],
                ),
              ).configBorderWidget(
                borderRadius: 24.r,
                borderColor: Colors.white.withOpacity(0.7),
                borderWidth: 1.w,
              ),
            ],
          ),

          // Join Team 按钮 - 使用 Transform 向上位移
          Transform.translate(
            offset: Offset(0, -25.h), // 向上位移25像素
            child: AnimatedTapButton(
              onTap: () {
                // 获取当前用户信息
                final currentUser = UserState.getCurrentUserInfo();
                if (currentUser == null) {
                  ToastWidget.showError('User not logged in');
                  return;
                }

                // 加入群聊
                final success = TeamConversationState.joinGroup(
                  group.groupId,
                  currentUser.userId,
                );

                if (success) {
                  // 关闭弹窗
                  Navigator.of(context).pop();
                  // 显示成功提示
                  ToastWidget.showSuccess('Successfully joined the group!');
                } else {
                  ToastWidget.showError('Failed to join the group');
                }
              },
              child: ClipRRect(
                borderRadius: BorderRadius.circular(14.r),
                child: BackdropFilter(
                  filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
                  child: Container(
                    width: 208.w,
                    height: 44.h,
                    decoration: BoxDecoration(
                      color: const Color(0x33FF8A3C),
                      borderRadius: BorderRadius.circular(14.r),
                      border: Border.all(
                        color: Colors.white.withOpacity(0.4),
                        width: 1.w,
                      ),
                    ),
                    child: Center(
                      child: Text('Join Team')
                          .fontSize(16.sp)
                          .textColor(Colors.white)
                          .fontWeight(FontWeight.w600)
                          .fontFamily(
                            GoogleFonts.quicksand(
                              fontWeight: FontWeight.w600,
                            ).fontFamily,
                          ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
